# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import logging

from absl import app, flags

from coin.base.datetime_util import (convert_string_to_dates, iterate_date)
from coin.support.feed_tool.feed_stats.logic.util import fetch_git_commit_sha_datetime
from coin.support.feed_tool.feed_stats.logic.feed_health_checker import run_feed_health_check

FLAGS = flags.FLAGS


def main(_):
  start_date = FLAGS.start_date
  assert start_date, '--start_date must be specified.'
  end_date = FLAGS.end_date
  assert end_date, '--end_date must be specified.'
  current_date = FLAGS.current_date

  start_date = convert_string_to_dates(start_date)[0]
  end_date = convert_string_to_dates(end_date)[0]
  trading_dates = [td for td in iterate_date(start_date, end_date)]

  db_config_file = FLAGS.db_config
  assert db_config_file, '--db_config must be specified.'
  git_commit = FLAGS.git_commit

  git_commit_datetime, git_commit_sha = fetch_git_commit_sha_datetime(git_commit)
  for trading_date in trading_dates:
    td_str = trading_date.strftime('%Y%m%d')
    print('\nRunning feed health check for %s ...' % td_str)
    run_feed_health_check(td_str, current_date, git_commit_sha, db_config_file)


if __name__ == '__main__':
  flags.DEFINE_string('start_date', None, 'yyyymmdd.')

  flags.DEFINE_string('end_date', None, 'yyyymmdd. Feed at end_date is not checked.')

  flags.DEFINE_string('current_date', None, 'yyyy-mm-dd. Default to be today.')

  flags.DEFINE_string('db_config', None, 'Database config file.')

  flags.DEFINE_string('git_commit', 'HEAD', 'Git commit sha or HEAD.')

  logging.basicConfig(level='DEBUG', format='%(levelname)8s %(asctime)s %(name)s] %(message)s')

  app.run(main)
